<template>
  <div>
    <el-dialog :title=istitle v-bind="dialogProps" :before-close="handleClose" :close-on-click-modal="false"
               :destroy-on-close="true" v-dialogDrag>
      <div @click="basicsShow()" style="cursor:pointer">
        <h3 style="color:#009688;"><i :class="classFont" style="margin-right: 5px;"></i>基础信息</h3>
      </div>
      <div style="width:100%;height:2px;background:#009688;margin-bottom: 10px;"></div>
      <!--  -->
      <el-form ref="Form" :rules="rules" :model="ruleForm" label-width="120px" class="demo-ruleForm"
               size="small" :disabled="isDisabled">

        <el-row :gutter="16" justify="start" v-show="formShow">
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="消缺工单名称:" prop="gdmc">
              <el-input v-model="ruleForm.gdmc" placeholder="请输入工单名称" @input="getTaskName" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="单位:" prop="xqdwbm">
              <el-select v-model="ruleForm.xqdwbm" placeholder="请选择单位" clearable style="width: 100%"
                         @change="onchange_gldw">
                <el-option v-for="item in zxoptions" :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="消缺站点:" prop="xqzdType">
              <el-select v-model="ruleForm.xqzdType" placeholder="请选择所属单位" clearable style="width: 100%"
                         @change="onchange_glbz">
                <el-option v-for="item in bzzxoptions" :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="showKf" :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="库房:" prop="sskf">
              <el-select v-model="ruleForm.sskf" placeholder="请选择所属单位" clearable style="width: 100%"
                         @change="onchange_sskf">
                <el-option v-for="item in sskfOptions" :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="!showKf" :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="能源站:" prop="ssjf">
              <!-- <el-select v-model="ruleForm.ssjf" placeholder="请选择所属单位" clearable style="width: 100%" @change="onchange_ssjf">
                  <el-option v-for="item in ssjfOptions" :key="item.value" :label="item.label"
                      :value="item.value">
                  </el-option>
              </el-select> -->
              <el-select v-model="ruleForm.ssjf" placeholder="请选择所属单位" clearable style="width: 100%"
                         @change="onchange_ssjf">
                <el-option v-for="item in ssjfOptions" :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="计划开始时间:" prop="jhkssj">
              <el-date-picker v-model="ruleForm.jhkssj" type="datetime" style="width:100%"
                              placeholder="请选择计划开始时间"
                              format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                              :picker-options="expireTimeOPtion" @change="handleJhkssj">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="计划结束时间:" prop="jhjssj">
              <el-date-picker v-model="ruleForm.jhjssj" type="datetime" style="width:100%"
                              placeholder="请选择计划开始时间"
                              format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
                              :picker-options="expireTimeOPtionJs">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="消缺主要内容:" prop="xqnr">
              <el-input v-model="ruleForm.xqnr" clearable type="textarea"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="创建人:" prop="createPersonName">
              <el-input v-model="ruleForm.createPersonName" placeholder="请输入创建人" clearable disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <el-form-item label="创建时间:" prop="createTime">
              <el-date-picker v-model="ruleForm.createTime" type="datetime" style="width:100%" clearable
                              placeholder="请选择创建时间" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>
      <div>
        <h3 style="color:#009688;">消缺隐患明细</h3>
      </div>
      <div style="width:100%;height:2px;background:#009688;margin-bottom: 10px;"></div>
      <div v-if="!isDisabled" style="margin-bottom: 10px;">
        <el-button type="primary" icon="fa fa-plus (alias)" @click="equipmentModel()">添加</el-button>
        <el-button icon="fa fa-times (alias)" @click="clearAll()">删除</el-button>
      </div>
      <vxe-table border stripe ref="selectedEquip" height="400" :data="list.data">
        <vxe-column type="seq" title="序号" width="60" align="center"></vxe-column>
        <vxe-column v-if="!isDisabled" type="checkbox" width="60" align="center"></vxe-column>
        <vxe-column field="unitName" align="center" title="单位名称" minWidth="200"></vxe-column>
        <vxe-column field="defectName" title="缺陷隐患名称" align="center" minWidth="150">
          <template v-slot="{ row }">
            <span @click="handleBaseInfo(row)">{{ row.defectName }}</span>
          </template>
        </vxe-column>
        <vxe-column field="handleTaskName" title="消缺工单名称" align="center" minWidth="150"></vxe-column>
        <vxe-column field="taskSourceName" title="数据来源" align="center" minWidth="150"></vxe-column>
        <vxe-column field="equipDefectTypeName" title="问题分类" align="center" minWidth="150"></vxe-column>
        <vxe-column field="creator" title="发现人" align="center" minWidth="150"></vxe-column>
        <!-- <vxe-column field="teamName" title="发现班组" align="center" minWidth="150"></vxe-column> -->
        <vxe-column field="creatTime" title="发现日期" align="center" minWidth="150"></vxe-column>
        <vxe-column field="defectParts" title="缺陷隐患部位" align="center" minWidth="150"></vxe-column>
        <vxe-column field="defectAddress" title="缺陷隐患地点" align="center" minWidth="150"></vxe-column>
        <vxe-column field="defectDescription" title="详细描述" align="center" minWidth="150"></vxe-column>
        <vxe-column field="equipName" title="设备名称" align="center" minWidth="150"></vxe-column>
        <vxe-column field="equipTypeName" title="设备类型" align="center" minWidth="150"></vxe-column>
        <vxe-column field="taskName" title="任务名称" align="center" minWidth="150"></vxe-column>
      </vxe-table>
      <vxe-pager perfect size="mini" :current-page="list.pageNo" :page-size="list.pageSize"
                 :page-sizes="list.pageSizes" :total="list.total"
                 :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                 @page-change="handlePageChange">
      </vxe-pager>
      <span slot="footer" class="dialog-footer" v-if="footerVisible">
                <el-button v-if="!isDisabled" @click="handleCancel()" :size="size"
                           icon="fa fa-minus-square-o">取消</el-button>
                <el-button v-if="!isDisabled" type="primary" @click="handleSubmit()" :size="size"
                           icon="fa fa-save (alias)">保存</el-button>
                <el-button v-if="isDisabled" type="primary" @click="handleCancel()" :size="size"
                           icon="fa fa-save (alias)">关闭</el-button>
            </span>
    </el-dialog>
    <selectEquipment ref="selectEquipment" @onSelectStations="onSelectStations"></selectEquipment>
    <baseInfo ref="baseInfo"></baseInfo>
  </div>
</template>
<script>
import {CommonApi} from '@/api/equip/CommonApi.js'
import {reactive} from "vue";
import {defectTaskFrom} from "../model/defectTaskFrom";
import selectEquipment from "./selectEquipment";
import baseInfo from "./baseInfo.vue"
import {defectTaskApi} from "@/api/defects/defectTaskApi";
import {workOrderManagement} from '@/api/defects/workOrderManagement.js'
import {getInfo} from "@/api/login";
import moment from "moment";
import {listDept} from "@/api/system/dept";

export default {
  components: {selectEquipment, baseInfo},
  data() {
    return {
      dwinfo: '',
      istitle: '新增消缺工单',
      dialogProps: {
        visible: false,
        // title: this.isEdit?'编辑消缺工单':'新增消缺工单',
        width: "70%",
        top: "5px",
      },

      footerVisible: true,
      size: "medium",
      ruleForm: reactive(defectTaskFrom).FormData,
      // rules: reactive(defectTaskFrom).rules,
      disabledForm: true,
      zxoptions: [],
      bzzxoptions: [],
      sskfOptions: [],
      ssjfOptions: [],
      xsnrShow: true,
      list: {
        data: [],
        pageNo: 1,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100],
        total: 0
      },
      row: {},
      classFont: 'fa fa-caret-down',
      formShow: true,
      isEdit: false,
      isDisabled: false,
      showKf: false,
      expireTimeOPtion: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7 //如果没有后面的-8.64e7就是不可以选择今天的
        }
      },
      expireTimeOPtionJs: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7 //如果没有后面的-8.64e7就是不可以选择今天的
        }
      }
    };
  },
  watch: {
  },
  computed: {
    rules() {
      const obj = {
        gdmc: "",
        xqdwbm: "",
        xqzdType: "",
        ssjf: "",
        sskf: '',
        jhkssj: '',
        jhjssj: '',
        xqnr: '',

      }
      const fields = Object.keys(obj)
      const rules = {}
      fields.forEach(d => {
        if (d == 'creator' || d == 'creatTime' || d == 'machineSanitation') {
          return

        } else {
          rules[d] = [
            {required: true, message: '不能为空',}
          ]
        }

      })

      return rules
    }
  },
  mounted() {

  },
  methods: {
    handlePageChange({currentPage, pageSize}) {
      this.loading = true
      this.list.pageNo = currentPage;
      this.list.pageSize = pageSize;
    },
    clearAll() {
      this.list.data = []
    },
    onSelectStations(data) {
      this.list.data = data
      this.list.total = data.length
      this.setTestTaskName()
    },
    showDialog(isEdit, row, isDisabled) {
      this.isEdit = isEdit
      this.isDisabled = isDisabled
      if (isEdit) {
        this.row = row
      } else {
        if (row) {
          this.row = row.row
        } else {
          this.row = {}
          // this.ruleForm={}
          // this.ruleForm = {}
          // this.list.data =[]

        }
      }
      this.istitle = isEdit ? '编辑消缺工单' : (isDisabled ? '消缺工单信息' : '新增消缺工单')
      this.istitle = isDisabled == 1 ? '消缺工单信息' : this.istitle
      this.initData(this.row, isEdit, isDisabled);


      // this.ruleForm.cjr = row.id
      // this.ruleForm.xqdw = row.
      this.dialogProps.visible = true;

      this.getOptionData_gldw()
      this.getOptionData_type()
    },
    basicsShow() {

      if (this.formShow) {
        this.formShow = false
        this.classFont = 'fa fa-caret-right'

      } else {
        this.formShow = true
        this.classFont = 'fa fa-caret-down'

      }

    },

    //选择设备弹窗
    equipmentModel() {
      console.log(this.ruleForm.xqdwbm)
      if (!this.ruleForm.xqdwbm) {
        this.$message.warning('请先选择单位！')
      } else {
        if ((!this.ruleForm.ssjf) && (!this.ruleForm.sskf)) {
          this.$message.warning('请先选择能源站或库房！')
        } else {
          this.$refs.selectEquipment.showDialog(this.list.data, this.ruleForm)
        }
      }
    },
    handleBaseInfo(row) {
      this.$refs.baseInfo.showDialog(row)
    },
    //编辑渲染
    initData(data, bool, isDisabled) {
      if (bool) {
        for (let key in this.ruleForm) {
          this.ruleForm[key] = data[key];
        }
        //   this.Event(data,bool,isDisabled)

        if (this.ruleForm.xqzdType === '0') {
          this.showKf = false
          defectTaskApi.getJfData(this.ruleForm.xqdwbm).then(res => {
            let optionList = [
              {label: '请选择', value: ''}
            ]
            res.data.forEach((item) => {
              optionList.push({label: item.jfName, value: item.id})
            })
            this.ssjfOptions = optionList

          })
        } else {
          this.showKf = true
          defectTaskApi.getKfData(this.ruleForm.xqdwbm).then(res => {
            let optionList = [
              {label: '请选择', value: ''}
            ]
            res.data.forEach((item) => {
              optionList.push({label: item.kfName, value: item.id})
            })
            this.sskfOptions = optionList

          })
        }
        workOrderManagement.getTaskEquipList(this.ruleForm.id).then(res => {
          this.list.data = res.data
        })

      } else {

        if (isDisabled) {
          for (let key in this.ruleForm) {
            this.ruleForm[key] = data[key];
          }
          if (this.ruleForm.xqzdType === '0') {
            this.showKf = false
            defectTaskApi.getJfData(this.ruleForm.xqdwbm).then(res => {
              let optionList = [
                {label: '请选择', value: ''}
              ]
              res.data.forEach((item) => {
                optionList.push({label: item.jfName, value: item.id})
              })
              this.ssjfOptions = optionList
            })
          } else {
            this.showKf = true
            defectTaskApi.getKfData(this.ruleForm.xqdwbm).then(res => {
              let optionList = [
                {label: '请选择', value: ''}
              ]
              res.data.forEach((item) => {
                optionList.push({label: item.kfName, value: item.id})
              })
              this.sskfOptions = optionList
            })
          }
          workOrderManagement.getTaskEquipList(this.ruleForm.id).then(res => {
            this.list.data = res.data
          })
        } else {
          // this.ruleForm =this.ruleForm
          for (let key in this.ruleForm) {
            this.ruleForm[key] = data[key];
          }
          this.list.data = []
          getInfo().then(res => {
            this.ruleForm.createPersonName = res.user.nickName
            this.ruleForm.createPerson = res.user.userId
            this.ruleForm.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
          })
          defectTaskApi.getDjbhData().then(res => {
            if (res.code === '200') {
              this.ruleForm.id = res.message
            }
          })
          this.ruleForm.xqzdType = '0'
          this.ruleForm.xqzdTypeName = '能源站'
          this.showKf = false
        }
      }
    },
    Event(data, bool, isDisabled) {
      if (bool) {
        console.log('11', bool)
        if (this.ruleForm.xqzdType === '0') {
          this.showKf = false
          defectTaskApi.getJfData(this.ruleForm.xqdwbm).then(res => {
            let optionList = [
              {label: '请选择', value: ''}
            ]
            res.data.forEach((item) => {
              optionList.push({label: item.jfName, value: item.id})
            })
            this.ssjfOptions = optionList

          })
        } else {
          console.log('22', bool)
          this.showKf = true
          defectTaskApi.getKfData(this.ruleForm.xqdwbm).then(res => {
            let optionList = [
              {label: '请选择', value: ''}
            ]
            res.data.forEach((item) => {
              optionList.push({label: item.kfName, value: item.id})
            })
            this.sskfOptions = optionList

          })
        }

        workOrderManagement.getTaskEquipList(this.ruleForm.id).then(res => {
          this.list.data = res.data
        })
      } else {
        console.log('33', bool)
        if (isDisabled) {
          for (let key in this.ruleForm) {
            this.ruleForm[key] = data[key];
          }
          if (this.ruleForm.xqzdType === '0') {
            this.showKf = false
            defectTaskApi.getJfData(this.ruleForm.xqdwbm).then(res => {
              let optionList = [
                {label: '请选择', value: ''}
              ]
              res.data.forEach((item) => {
                optionList.push({label: item.jfName, value: item.id})
              })
              this.ssjfOptions = optionList
            })
          } else {
            this.showKf = true
            defectTaskApi.getKfData(this.ruleForm.xqdwbm).then(res => {
              let optionList = [
                {label: '请选择', value: ''}
              ]
              res.data.forEach((item) => {
                optionList.push({label: item.kfName, value: item.id})
              })
              this.sskfOptions = optionList
            })
          }
          workOrderManagement.getTaskEquipList(this.ruleForm.id).then(res => {
            this.list.data = res.data

          })
        } else {
          console.log('34', bool)
          this.ruleForm = {}
          this.list.data = []
          getInfo().then(res => {
            this.ruleForm.createPersonName = res.user.nickName
            this.ruleForm.createPerson = res.user.userId

          })
          defectTaskApi.getDjbhData().then(res => {
            if (res.code === '200') {
              this.ruleForm.id = res.message
            }
          })
          this.ruleForm.xqzdType = '0'
          this.ruleForm.xqzdTypeName = '能源站'
          this.showKf = false
        }
      }
    },
    getTaskName(event) {
      // if (event.target.value !== undefined) {
      //     this.ruleForm.gdmc = event.target.value
      // } else {
      //     this.ruleForm.gdmc = ''
      // }

    },
    setTestTaskName() {
      const xqdwbm = this.zxoptions.find(d => d.value === this.ruleForm.xqdwbm) ? this.zxoptions.find(d => d.value === this.ruleForm.xqdwbm).label : ''
      this.ruleForm.gdmc = xqdwbm + (this.list.data.length > 0 ? (this.list.data[0].defectName + '等' + (this.list.data.length) + '个') : '') + '消缺工单'
    },
    DateDiff(sDate1) {

      var oDate1, oDate2, iDays
      oDate1 = Date.parse(new Date(sDate1).toLocaleDateString())
      oDate2 = Date.parse(new Date().toLocaleDateString())
      iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24)    //把相差的毫秒数转换为天数
      return iDays
    },
    handleJhkssj(val) {
      var num = this.DateDiff(val)
      this.expireTimeOPtionJs = {
        disabledDate(time) {
          return time.getTime() < new Date().getTime() + 8.64e7 * num  //如果没有后面的-8.64e7就是不可以选择今天的
        }
      }
    },
    //确定
    handleSubmit() {
      this.$refs.Form.validate((valid) => {
        if (valid) {

          this.list.data.forEach((d) => {
            d.defectsId = d.id
          })
          this.ruleForm.defectsSheetRelVoList = this.list.data
          if (!this.isEdit) {
            defectTaskApi.insert(this.ruleForm).then(res => {
              this.dialogProps.visible = false;
              this.$message.success('新增成功')

              this.$emit("closeEvent");
            })
          } else {
            defectTaskApi.update(this.ruleForm).then(res => {
              this.dialogProps.visible = false;
              this.$message.success('修改成功')

              this.$emit("closeEvent");
              this.isEdit = false
            })
          }
        } else {
          console.log("222")
          return false;
        }
      });
    },

    //取消
    handleCancel() {
      this.$refs.Form.resetFields()
      // for (const k in this.form.data) {
      //   this.form.data[k] = ''
      // }
      this.list = {
        data: [],
      }
      this.row = {}

      this.dialogProps.visible = false;
    },
    //确定关闭
    handleClose(done) {
      // this.$confirm("确认关闭？")
      //     .then((_) => {
      this.handleCancel()
      this.dialogProps.visible = false;
      // })
      // .catch((_) => { });
    },
    getOptionData_type() {
      CommonApi.queryDictData('EN_DEFECTS_SSZDLX').then(res => {
        // 修改编辑框
        // const sexColumn = $grid.getColumnByField('sex')
        // sexColumn.editRender.options = sexList
        // 修改查询条件列表
        let optionList = [
          {label: '请选择', value: ''}
        ]
        res.data.forEach((item) => {
          optionList.push({label: item.value, value: item.code})
        })
        this.bzzxoptions = optionList
      }).catch(err => {
        console.log(err)
      })
    },
    getOptionData_gldw() {//获取管理单位：字典表
      getInfo().then(res => {
        this.ruleForm.createPersonName = res.user.nickName
        this.ruleForm.createPerson = res.user.userId
        this.ruleForm.createTime = moment().format('YYYY-MM-DD HH:mm:ss')

        let params = {
          deptId: res.user.dept.deptId,
          parentId: ''
        }
        listDept(params).then(result => {
          this.dwinfo = result.data

          let optionList = [
            {label: '请选择', value: ''}
          ]
          result.data.forEach((item) => {
            optionList.push({label: item.deptName, value: item.deptId})

          })
          this.zxoptions = optionList
        })

      })
    },
    onchange_gldw(val) {
      this.ruleForm.ssjf = ''
      this.ruleForm.sskf = ''
      // this.ruleForm.xqzdType=''
      this.setTestTaskName()
      this.list.data = []
      this.ruleForm.xqdwmc = ''
      if (val) {
        let arr = this.zxoptions.filter(item => {
          return item.value == val;
        })
        if (arr && arr.length > 0) {
          this.ruleForm.xqdwmc = arr[0].label;
        }
      }
      if (this.ruleForm.xqzdType === '0') {
        defectTaskApi.getJfData(val).then(res => {
          let optionList = []
          res.data.forEach((item) => {
            optionList.push({label: item.jfName, value: item.id})
          })
          this.ssjfOptions = optionList
        })
      } else {
        defectTaskApi.getKfData(val).then(res => {
          let optionList = []
          res.data.forEach((item) => {
            optionList.push({label: item.kfName, value: item.id})
          })
          this.sskfOptions = optionList
        })
      }
    },
    onchange_glbz(val) {
      if (val == '') {
        this.sskfOptions = []
        this.ssjfOptions = []
        this.ruleForm.sskf = ''
        this.ruleForm.sskfmc = ''
        this.ruleForm.ssjf = ''
        this.ruleForm.ssjfmc = ''
      }
      this.list.data = []
      this.ruleForm.xqzdTypeName = ''
      if (val) {
        let arr = this.bzzxoptions.filter(item => {
          return item.value == val;
        })
        if (arr && arr.length > 0) {
          this.ruleForm.xqzdTypeName = arr[0].label;
        }
      }
      if (val === '0') {
        this.ruleForm.sskf = ''
        this.ruleForm.sskfmc = ''
        this.showKf = false
        defectTaskApi.getJfData(this.ruleForm.xqdwbm).then(res => {
          let optionList = []
          res.data.forEach((item) => {
            optionList.push({label: item.jfName, value: item.id})
          })
          this.ssjfOptions = optionList
        })
      } else if (val == '1') {
        this.ruleForm.ssjf = ''
        this.ruleForm.ssjfmc = ''
        this.showKf = true
        defectTaskApi.getKfData(this.ruleForm.xqdwbm).then(res => {
          let optionList = []
          res.data.forEach((item) => {
            optionList.push({label: item.kfName, value: item.id})
          })
          this.sskfOptions = optionList
        })
      }
    },
    onchange_sskf(val) {
      this.list.data = []
      this.ruleForm.sskfmc = ''
      if (val) {
        let arr = this.sskfOptions.filter(item => {
          return item.value == val;
        })
        if (arr && arr.length > 0) {
          this.ruleForm.sskfmc = arr[0].label;
        }
      }
    },
    onchange_ssjf(val) {
      this.list.data = []
      this.ruleForm.ssjfmc = ''
      if (val) {
        let arr = this.ssjfOptions.filter(item => {
          return item.value == val;
        })
        if (arr && arr.length > 0) {
          this.ruleForm.ssjfmc = arr[0].label;
        }
      }
    },
  },
};
</script>
<style>
.el-dialog__footer {
  width: 100%;
  border-top: 1px solid #e8e8e8;
}
</style>
